<template>
  <div class="container">
    <el-form
      :model="settlementData"
      :rules="$rules"
      class="grid-flex"
      label-width="9rem"
      ref="formRef"
    >
      <el-form-item
        :label="$language.local('MID')"
        prop="mid"
      >
        <select-merchantid
          disabled
          v-model="settlementData.mid"
        ></select-merchantid>
      </el-form-item>
      <el-form-item :label="$language.local('SPID')">
        <xy-input
          :value="`${task.BusinessNo} - ${task.projectName}`"
          disabled
        ></xy-input>
        <!-- <select-id
          api-name="/api/ServiceProject/GetList"
          disabled
          v-model="settlementData.spid"
        >
          <template #options="{ options }">
            <el-option
              :key="item.ID"
              :label="`${item.ID} - ${item.projectName} - ￥${item.Amount}`"
              :value="item.ID"
              v-for="item in options"
            ></el-option>
          </template>
        </select-id>-->
      </el-form-item>
      <el-form-item
        :label="$language.local('TaskTotalAmount')"
        prop="TaskTotalAmount"
      >
        <xy-input
          disabled
          v-model="settlementData.TaskTotalAmount"
        ></xy-input>
      </el-form-item>
      <el-form-item
        :label="$language.local('CanSettlementAmount')"
        prop="CanSettlementAmount"
      >
        <xy-input
          disabled
          v-model="settlementData.CanSettlementAmount"
        ></xy-input>
      </el-form-item>
      <el-form-item
        :label="$language.local('Amount')"
        :rules="AmountRule"
        prop="Amount"
      >
        <xy-input
          disabled
          placeholder="结算金额以上传的结算明细为准"
          v-model="settlementData.Amount"
        ></xy-input>
      </el-form-item>
      <el-form-item
        :label="$language.local('TSKSettlementType')"
        prop="TSKSettlementType"
      >
        <select-settlementmode v-model="settlementData.TSKSettlementType"></select-settlementmode>
      </el-form-item>
      <el-form-item
        :label="$language.local('PayType')"
        prop="PayType"
      >
        <el-select v-model="settlementData.PayType">
          <el-option
            :value="1"
            label="银行卡"
          ></el-option>
          <el-option
            :value="2"
            label="支付宝"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        :error="settlementError"
        :label="$language.local('ExcelUrl')"
        class="upload-file"
        prop="ExcelUrl"
      >
        <div class="row">
          <upload-file
            :on-success="handleSuccessed"
            v-model="settlementData.ExcelUrl"
          ></upload-file>
          <a
            class="ml-2"
            href="http://demo.xinyueai.com/admin/static/template/Settlementtemplate.xlsx"
            target="_blanK"
          >
            <i class="el-icon-download"></i> 下载模板
          </a>
        </div>
      </el-form-item>
      <!-- <el-form-item
        prop="otherSettlementModes"
        v-if="settlementData.TSKSettlementType == 4"
      >
        <xy-input v-model="settlementData.otherSettlementModes"></xy-input>
      </el-form-item>-->
    </el-form>
    <div
      :style="`height:${employees.length * 200}px`"
      class="emp-table pb-1"
      v-if="employees.length > 0"
    >
      <xy-table :list="employees">
        <template #addItem>
          <span></span>
        </template>
        <template #operation>
          <span></span>
        </template>
        <template #pagination>
          <span></span>
        </template>
      </xy-table>
    </div>

    <el-radio-group
      class="row jcc mt-4"
      v-if="'Check' in auth && action === 'check'"
      v-model="checkstatus"
    >
      <el-radio :label="1">审核通过－可进行代付</el-radio>
      <el-radio :label="2">审核不通过</el-radio>
    </el-radio-group>
    <div class="form-footer pb-2">
      <div>
        <el-button
          @click="$router.go(-1)"
          icon="el-icon-back"
        >返 回</el-button>
        <el-button
          :disabled="!!settlementError"
          @click="onSubmit('formRef')"
          icon="el-icon-check"
          type="primary"
        >确定</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import API from "../../plugins/api";
export default {
  data() {
    const validateAmount = (rule, value, callback)=>{
      if (this.settlementData.Amount > this.settlementData.CanSettlementAmount) {
        callback(new Error("结算金额不可大于可结算金额！"));
      }else{
        callback();
      }
    };
    return {
      task: {
        ID: 72,
        Ctime: "2021-07-14T17:06:35",
        PostName: "",
        checkdate: "2021/7/14 17:06:35",
        finashdate: "",
        takingdate: "2021/7/14 17:06:35",
        paydate: "",
        projectName: "开发小程序1",
        BusinessNo: "BN20210714170635",
        MID: 177,
        ServiceType: "",
        WorkContent:
          "聘的人员必须遵守国家法律、法规；遵守贵公司的各项规章制度；忠于职守",
        PerformanceFeeSettlementRules: "业绩结算佣金，具体以单品业绩结算为准",
        Status: 0,
        SID: 0,
        ExportInResult: "",
        TskType: 1,
        TskStatus: 3,
        ServiceName: "",

        BegTime: "2021-02-01",
        EndTime: "2021-05-20",
        Amount: 50000,
        TAID: 0,
        attFileName: "",
        attFilePath:
          "/upload/clientUp/3d27fe5f-eb64-4087-8420-52a821302dc8.xlsx",
        TskEmpFile: "",
        recruitPerson: 0,
        SettlementModes: 2,
        otherSettlementModes: "",
        RecruitmentRequirements: "大中专应届毕业生等。",
        checker: "",
        checkstatus: -1,
        checkerId: 0,
        Reason: "",
        taskRegionP: "湖南省",
        taskRegionC: "长沙",
      },
      settlementData: {
        spid: "",
        mid: "",
        TaskTotalAmount: "",
        Amount: "",
        TSKSettlementType: 2,
        CanSettlementAmount: "",
        otherFile: "",
        PreviousId: "",
        pay: "",
        PayType: 2,
        ExcelUrl: "",
      },
      settlementError: "",
      checkstatus: -1,
      empApi: new API("/api/employee/GetList"),
      empTableParam: {
        auditStatus: 1,
      },
      employeesColumns: {
        EmpName: "梁由之",
        IdCardNo: "510724198510242428",
        BankCardNo: "6228460480014077810",
        EmpPhone: "13678289922",
      },

      AmountRule: [
        { required: true, message: "不能为空", trigger: "blur" },
        { validator: validateAmount, trigger: "blur" },
      ],
      employees: [],
      id: 0,
      auth: this.$store.getters.rights[this.$route.matched[1].path.slice(1)],
    };
  },
  created() {
    this.getTask();
    console.log(this.auth);
    // this.getEemloyee();
  },
  methods: {
    async getTask() {
      const { id, action, CanSettlementAmount } = this.$route.query;
      this.action = action;
      this.id = id;
      const response = await this.$http.get(
        `/api/ServiceProject/GetModel/${id}`
      );

      console.log(response);
      let temp = { ...response.data.Data };
      this.settlementData.spid = id;
      this.settlementData.mid = temp.mid;
      this.settlementData.TaskTotalAmount = temp.Amount;
      this.settlementData.CanSettlementAmount = CanSettlementAmount;
      this.task = response.data.Data;
      console.log(this.task);
    },
    async onCheck() {
      await this.$http.post(
        `/api/TSKSettlement/Check/${this.id}?checkstatus=${this.checkstatus}`
      );
    },
    async onSubmit(formName) {
      await this.$refs[formName].validate();
      const response = await this.$http.post(
        "/api/TSKSettlement/batchInputSettlementData",
        null,
        this.settlementData
      );
      console.log(response);
      this.$router.replace("/TSKSettlement");
    },
    /**
     * 导入明细成功后回调
     * @param { Object }  {url,name}
     */
    async handleSuccessed(e) {
      console.log(e);
      let response;
      try {
        response = await this.$http.post(
          `/api/TSKSettlement/CheckSettlementData?ExcelUrl=${e.docurl}&spid=${this.settlementData.spid}&mid=${this.settlementData.mid}`
        );
      } catch (error) {
        this.settlementError = error.data.Message;
        throw error;
      }

      this.employees = response.data.Data;
      console.log(this.employees);
      let acount = 0;
      let isError = this.employees.every((cur) => {
        acount += Number(cur.amount);
        if (cur.Error !== "") {
          this.settlementError = cur.EmpName + cur.Error;
          return false;
        } else {
          return true;
        }
      });

      if (isError) {
        this.settlementData.Amount = acount;
        this.settlementError = "";
      }
      // this.settlementData.Amount = this.employees.reduce(
      //   (total, cur) => total + Number(cur.amount),
      //   0
      // );
      console.log(this.employees);
      console.log(this.settlementData.Amount);
      // response.data.Data.forEach((v) => {
      //   this.orderEmployees.push(v.Id);
      // });
      // console.log(this.orderEmployees);
      // this.orderEmployees
    },
  },
};
</script>

<style lang="less" scoped>
// .settlement-table {
//   padding-bottom: 60px;
//   position: relative;
// }
</style>
